<script setup lang="ts">
import { getHomeGoodsGuessLikeAPI } from '@/services'
import type { GuessItem, PageParams } from '@/types'
import { ref } from 'vue'
import { onMounted } from 'vue'

// Required泛型工具-将类型的所有属性变为必选
const pageParams: Required<PageParams> = {
  // page: import.meta.env.DEV ? 30 : 1,
  page: 1,
  pageSize: 10,
}
const guessList = ref<GuessItem[]>([])
// 数据是否加载中标记，用于防止上拉加载触发多次请求（节流优化）
const isLoading = ref(false)
// 数据是否加载完毕标记
const isFinish = ref(false)
// 获取猜你喜欢数据
const getHomeGoodsGuessLikeData = async () => {
  if (isLoading.value) return
  if (isFinish.value) {
    return uni.showToast({ icon: 'none', title: '没有更多数据' })
  }
  isLoading.value = true
  const res = await getHomeGoodsGuessLikeAPI(pageParams)
  guessList.value.push(...res.result.items)
  isLoading.value = false
  if (pageParams.page < res.result.pages) {
    pageParams.page++
  } else {
    isFinish.value = true
  }
}
onMounted(() => {
  getHomeGoodsGuessLikeData()
})

// 重置组件数据
const resetData = () => {
  pageParams.page = 1
  guessList.value = []
  isFinish.value = false
}

// 暴露方法供外部使用
defineExpose({
  getMore: getHomeGoodsGuessLikeData,
  resetData,
})
</script>

<template>
  <view class="caption">
    <text class="text">猜你喜欢</text>
  </view>
  <view class="guess">
    <navigator
      class="guess-item"
      v-for="item in guessList"
      :key="item.id"
      :url="`/pages/goods/goods?id=${item.id}`"
    >
      <image class="image" mode="aspectFill" :src="item.picture"></image>
      <view class="name"> {{ item.name }} </view>
      <view class="price">
        <text class="small">¥</text>
        <text>{{ item.price }}</text>
      </view>
    </navigator>
  </view>
  <view class="loading-text">
    {{ isFinish ? '- 没有更多数据 -' : '正在加载...' }}
  </view>
</template>

<style lang="scss">
@import '@/components/styles/XtxGuess.scss';
</style>
